Ext.require(['*']);

Ext.define('modelTipoItems', {
	extend: 'Ext.data.Model',
	proxy : {
		type : 'ajax',
		//actionMethods : 'POST',
		//url : '/roles', //application/controllers/Habitacion.php
		
		api: {
                read: '/items/viewTipoItems'
                //create: '/roles/create',
                //save: '/roles/update',
                //destroy: '/roles/destroy'
		},
	
		reader: {
				
                type: 'json',
                successProperty: 'success',
                root: 'tiposItems',
                messageProperty: 'message'
            }
	},
	
	fields: [
		{type: 'int' , name: 'idTipoItem'},
		{type: 'string', name: 'nombreTipoItem'}
		
			]
});





Ext.onReady(function () {
    
    //DataStore para el ComboBox de la lista de Tipos de Items
	this.dsCmbTipoItems = Ext.create('Ext.data.Store', {
		model : 'modelTipoItems',
		autoLoad : true
	}); 
    
    //ComboBox para mostrar los tipos de items disponibles
	this.cmbTiposItems = Ext.create(/*'Ext.form.ComboBox'*/'Ext.ux.form.field.BoxSelect', {
					
		fieldLabel: 'Tipo de Item',
		name : 'cmb_tiposItems',
		id: 'id_cmb_tiposItems',
		displayField: 'nombreTipoItem',
		width: 500,
		//height: 70,
		//labelWidth: 130,
		store: this.dsCmbTipoItems,
		queryMode: 'local',
		emptyText: 'Seleccione un Tipo de Item',
		valueField: 'idTipoItem',
		multiSelect :false,
		allowBlank : false,
		listeners:{
            scope: this,
            'select': function(combo, rec, idx){
                //onUpdateClick(combo, rec, idx)
				console.log(combo);
				console.log(rec);
				console.log(idx);
				idTipoItemEnviar = combo.value;
				console.log(idTipoItemEnviar);
				
				//traemos los permisos que tiene el rol que estamos editando
				Ext.Ajax.request(
				{
					url:'/items/traerAtributos',
					//form:"[STICK FORM ID HERE]",
					method:'GET',
					scope : this,
					params: { idTipoItem: idTipoItemEnviar},
					success: function(response, opts) {
						//alert("successfull");
						obj = Ext.decode(response.responseText)
						//Ext.getCmp('id_cmbx_permisos').setValue(obj.permisos)
						
						panelExiste = Ext.getCmp('id_datos_fields_item');
						//console.log('panel existente:');
						//console.log(panelExiste);
						
						if(panelExiste != null){
							panelExiste.destroy();
							
						}
						
						atributos = obj.atributos;
						//console.log(atributos);
						
						campos = [];
						
						for(index in atributos){
							console.log(atributos[index]);
							
							tipoAux = 'textfield';
							anchorAux = '80%';
							if(atributos[index].tipo == 'Fecha'){
								anchorAux = '40%';
								tipoAux = 'datefield';
							}
							
							campos.push({fieldLabel:atributos[index].nombre, name: 'campo' + index, xtype : tipoAux, anchor: anchorAux});
						}
						
						
						Ext.getCmp('id_panel_nuevo_item').add(Ext.widget('closablefieldset', {
							columnWidth: 0.5,
							id:'id_datos_fields_item',
							title: 'Atributos',
							collapsible: true,
							defaultType: 'textfield',
							defaults: { anchor: '100%' },
							layout: 'anchor',
							items: campos
						}));
						
					},
					failure:function(res,opt) {
						alert("request failed");
					}
				});
				
            }                           
        }

	}); 
    
    
    
    Ext.define('Ext.form.ClosableFieldSet', {
        extend: 'Ext.form.FieldSet',
        alias: 'widget.closablefieldset'
        /*initLegend: function () {
            var me = this;
            me.callParent(arguments);
            if (!me.legend.closable) {
                me.legend.insert(1, Ext.widget('tool', {
                    type: 'close',
                    handler: me.onCloseClick,
                    scope: me
                }));
                me.legend.closable = true;
            }
        },
        onCloseClick: function () {
            if (this.ownerCt) {
                this.ownerCt.remove(this, true);
            }
        }*/
    });
    Ext.create('Ext.form.Panel', {
        title: 'Nuevo Item',
        name: 'panel_nuevo_item',
        id: 'id_panel_nuevo_item',
        bodyPadding: 10,
        width: 550,
        renderTo: Ext.getBody(),
        /*tbar: [
            {
                text: 'Add FieldSet',
                handler: function () {
                    this.up('form').add(Ext.widget('closablefieldset', {
                        columnWidth: 0.5,
                        title: 'Test Fieldset',
                        collapsible: true,
                        defaultType: 'textfield',
                        defaults: { anchor: '100%' },
                        layout: 'anchor',
                        items: [
                            {
                                fieldLabel: 'Field 1',
                                name: 'field1'
                            },
                            {
                                fieldLabel: 'Field 2',
                                name: 'field2'
                            }
                        ]
                    }));
                }
            }
        ],*/
        items: [
            {
                xtype: 'closablefieldset',
                columnWidth: 0.5,
                title: 'Creación de nuevo Item',
                //collapsible: true,
                defaultType: 'textfield',
                defaults: { anchor: '100%' },
                layout: 'anchor',
                items: [
                    {
                        fieldLabel: 'Código',
                        name: 'id_codigo',
                        anchor: '40%'
                    },
					{
						xtype : 'fieldcontainer',
						anchor: '70%',
						labelStyle : 'font-weight:bold;padding:0',
						items: [
							this.cmbTiposItems,
						]
					}
                
                ]
            }
        ],
        
        buttons: 
        [
			{
				text : 'Guardar',
				id : 'id_btn_add_guardar_item',
				iconCls : 'icon_button_save',
				scope : this
				//handler : this.HandlerGuardarDatosRol
			},
			{
				text : 'Cancelar',
				id : 'id_btn_add_cancelar_item',
				iconCls : 'icon_button_cancel',
				scope : this,
				handler : function(){
					//this.WindowFormAddModal.close();
				}
			}
		]
    });
}); 
